﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using KVB.Common;
using Customer_Profile.eCard.DBDao;
using Customer_Profile.Admin;

namespace Customer_Profile.eCard.Settle
{
    public partial class Paysub : System.Web.UI.Page
    {
        string str_id = "";
        DataSet dsAgent = null;
        DataSet dsPaymethod = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["id"] != null)
            {
                str_id = Request["id"].ToString();
                if (str_id.Equals("null"))
                {
                    return;
                }
            }
            else
            {
                return;
            }
            dsAgent = SaleAgentDao.getSettleAgentList("Y");
            dsPaymethod = Comm.getTypeList("SettlePayMethod");

            if (!Page.IsPostBack)
            {
                bindSubGrid(str_id);
            }            
        }

        private void bindSubGrid(string str_id)
        {
            try
            {
                DataSet ds = null;
                ds = DealDao.getSettleSubList(str_id);
                rpt.DataSource = ds;
                rpt.DataBind();
            }
            catch (Exception ex)
            {
                lblWarning.Text = ex.ToString();
            }              
        }

        protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
        { 
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DropDownList dllOperator = (DropDownList)e.Item.FindControl("dropPaymethod");
                dllOperator.DataSource = dsPaymethod;
                dllOperator.DataTextField = "codeName";
                dllOperator.DataValueField = "codeValue";
                dllOperator.DataBind();
                HiddenField hidPaymethod = (HiddenField)e.Item.FindControl("hidPayMethod");
                if (hidPaymethod.Value != null && hidPaymethod.Value != "")
                {
                    dllOperator.Items.FindByValue(hidPaymethod.Value).Selected = true;
                }
                else
                {
                    dllOperator.SelectedIndex = 0;
                }
                
                DropDownList dllSettleAgent = (DropDownList)e.Item.FindControl("dropSettleAgent");                
                dllSettleAgent.DataSource = dsAgent;
                dllSettleAgent.DataTextField = "settle_agent_name";
                dllSettleAgent.DataValueField = "settle_agent_id";
                dllSettleAgent.DataBind();
                HiddenField hidSettleAgentid = (HiddenField)e.Item.FindControl("hidSettleAgent");
                if (hidSettleAgentid.Value != null && hidSettleAgentid.Value != "" && hidSettleAgentid.Value != "0")
                {
                    dllSettleAgent.Items.FindByValue(hidSettleAgentid.Value).Selected = true;
                }
                else
                {
                    dllSettleAgent.SelectedIndex = 0;
                }

                //btnConfirm   hidStatus
                Button btnConfirmTemp = (Button)e.Item.FindControl("btnConfirm");
                Button btnOrderTemp = (Button)e.Item.FindControl("btnOrder");
                HiddenField hidStatusTemp = (HiddenField)e.Item.FindControl("hidStatus");               
                if (hidStatusTemp.Value.Trim().Equals("PASS"))
                {
                    btnConfirmTemp.Enabled = false;
                    btnOrderTemp.Enabled = false;
                }
                if (hidStatusTemp.Value.Trim().Equals("SO"))
                {
                    btnOrderTemp.Enabled = false;
                }
            }
        }

        protected void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            #region 支付确认
            if (e.CommandName == "btnConfirm")
            {
                int settle_id = int.Parse(e.CommandArgument.ToString());
                //mmdeals更新状态，解锁,更新手续费，付款方式，结算代理商
                //更新settleSub_info
                string status = "";
                string message = "";
                DropDownList dllpayMethod = (DropDownList)e.Item.FindControl("dropPaymethod");
                string pay_method = dllpayMethod.SelectedItem.Value;
                DropDownList dllSettleAgent = (DropDownList)e.Item.FindControl("dropSettleAgent");
                string settle_agent_id = dllSettleAgent.SelectedItem.Value;

                TextBox txtSettleAmount = (TextBox)e.Item.FindControl("txtSettle_amount");
                TextBox txtBankFee = (TextBox)e.Item.FindControl("txtNetbank_fee");
                TextBox txtSettleFee = (TextBox)e.Item.FindControl("txtSettle_fee");
                TextBox txtPayAmount = (TextBox)e.Item.FindControl("txtPayAmount");
                //decimal payAmount= decimal.Parse(txtSettleAmount.Text) - decimal.Parse(txtSettleFee.Text);
                //txtPayAmount.Text = payAmount.ToString(); 

                if (txtBankFee.Text.Trim().Equals("") || txtSettleFee.Text.Trim().Equals(""))
                {
                    lblWarning.Text = "手续费，结算费，支付金额不能为空";
                    return;
                }

                try
                {
                    decimal dpay_amount = decimal.Parse(txtPayAmount.Text);
                    decimal dSettle_fee = decimal.Parse(txtSettleFee.Text);
                    decimal dNetBankFee = decimal.Parse(txtBankFee.Text);

                    DataSet dsDealbalance = DealDao.getDealBalance_bySettleid(settle_id.ToString());
                    if (!Comm.DataSetIsEmpty(dsDealbalance))
                    {
                        //检查一下是否有多笔在申请中的情况。
                        if (DealDao.check_ifRepeat_requestSettle(settle_id.ToString()))
                        {
                            KVB.Common.Log.WriteDefaultLog("支付确认发现结算复核审核：", settle_id + "存在多笔未结束的结算申请。");                            
                            KVB.Common.JavaScript.ViewAlertMsg("支付确认失败！settle id :" + settle_id + ":改笔原始交易存在多笔未结束的结算申请！请联系总部确认;");
                        }
                        else
                        {
                            decimal _dDealbalance = Convert.ToDecimal(dsDealbalance.Tables[0].Rows[0][0].ToString());
                            //如果余额足够。
                            if (_dDealbalance >= dpay_amount + dSettle_fee)
                            {
                                DealDao.confirmPay(settle_id, settle_agent_id, pay_method, dNetBankFee, dSettle_fee, dpay_amount, out status, out message);
                                if (status.Equals("Y"))
                                {
                                    //重新绑定
                                    bindSubGrid(str_id);
                                    lblWarning.Text = "";
                                    KVB.Common.JavaScript.ViewAlertMsg("结算成功！");
                                }
                                else
                                {
                                    lblWarning.Text = message;
                                }
                            }
                            else
                            {
                                KVB.Common.JavaScript.ViewAlertMsg("付款确认失败，卡内余额不足！");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    lblWarning.Text = ex.ToString();
                    Log.WriteDefaultLog("rpt_ItemCommand_Paysub", ex.ToString());
                }
            }
            #endregion

            #region 安排付款
            if (e.CommandName == "btnOrder")
            {
                int settle_id = int.Parse(e.CommandArgument.ToString());
                DropDownList dllpayMethod = (DropDownList)e.Item.FindControl("dropPaymethod");
                string pay_method = dllpayMethod.SelectedItem.Value;
                DropDownList dllSettleAgent = (DropDownList)e.Item.FindControl("dropSettleAgent");
                string settle_agent_id = dllSettleAgent.SelectedItem.Value;

                TextBox txtBankFee = (TextBox)e.Item.FindControl("txtNetbank_fee");
                TextBox txtSettleFee = (TextBox)e.Item.FindControl("txtSettle_fee");
                TextBox txtPayAmount = (TextBox)e.Item.FindControl("txtPayAmount");

                decimal dpay_amount = decimal.Parse(txtPayAmount.Text);
                decimal dSettle_fee = decimal.Parse(txtSettleFee.Text);
                decimal dNetBankFee = decimal.Parse(txtBankFee.Text);

                //检查一下是否有多笔在申请中的情况。
                if (DealDao.check_ifRepeat_requestSettle(settle_id.ToString()))
                {
                    KVB.Common.Log.WriteDefaultLog("安排付款发现结算复核审核：", settle_id + "存在多笔未结束的结算申请。");                    
                    KVB.Common.JavaScript.ViewAlertMsg("安排付款失败！settle id :" + settle_id + ":改笔原始交易存在多笔未结束的结算申请！请联系总部确认;");
                }
                else
                {
                    //1,检查余额是否足够。
                    DataSet dsDealbalance = DealDao.getDealBalance_bySettleid(settle_id.ToString());
                    if (!Comm.DataSetIsEmpty(dsDealbalance))
                    {
                        decimal _dDealbalance = Convert.ToDecimal(dsDealbalance.Tables[0].Rows[0][0].ToString());
                        //如果余额足够。
                        if (_dDealbalance >= dpay_amount + dSettle_fee)
                        {
                            string status = "";
                            string message = "";
                            try
                            {
                                DealDao.confirmOrder(settle_id, settle_agent_id, pay_method, dNetBankFee, dSettle_fee, dpay_amount, out status, out message);
                                if (status.Equals("Y"))
                                {
                                    bindSubGrid(str_id);
                                    lblWarning.Text = "";
                                    KVB.Common.JavaScript.ViewAlertMsg("付款安排成功！");
                                }
                                else
                                {
                                    lblWarning.Text = message;
                                }
                            }
                            catch (Exception ex)
                            {
                                lblWarning.Text = ex.ToString();
                                Log.WriteDefaultLog("rpt_ItemCommand_Paysub", ex.ToString());
                            }
                        }
                        else
                        {
                            KVB.Common.JavaScript.ViewAlertMsg("付款安排失败，卡内余额不足！");
                        }
                    }
                    else
                    {
                        KVB.Common.JavaScript.ViewAlertMsg("付款安排失败，无法取到卡内余额！");
                    }
                }
            }
            #endregion
        }
    }
}